package agents;

import jade.core.AID;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
  @author Marcin Harasimczuk
  
  Based on example by Giovanni Caire - TILAB
 */
class ClassifierAgentGui extends JFrame {	
	
	ClassifierAgentGui(ClassifierAgent a) {
		super(a.getLocalName());
		
		myAgent = a;
		this.setTitle(a.getName());
		
		JPanel p = new JPanel();
		p.setLayout(new GridLayout(5, 1));
		p.add(new JLabel("Agent name: " + a.getName().split("@")[0]));
		p.add(new JLabel("Command:"));
		mCommandField = new JTextField(30);
		p.add(mCommandField);
		p.add(new JLabel("Reply:"));
		mReplyField = new JTextField(30);
		mReplyField.setEditable(false);
		p.add(mReplyField);
		
		getContentPane().add(p, BorderLayout.CENTER);
		
		JButton sendButton = new JButton("Send");
		sendButton.addActionListener( new ActionListener() {
			public void actionPerformed(ActionEvent ev) {
				try {
					String command = mCommandField.getText().trim();
					myAgent.parseCommand(command);
					mCommandField.setText("");
				}
				catch (Exception e) {
					JOptionPane.showMessageDialog(ClassifierAgentGui.this, "Invalid values. "+e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); 
				}
			}
		} );
		p = new JPanel();
		p.add(sendButton);
		getContentPane().add(p, BorderLayout.SOUTH);
		
		// Make the agent terminate when the user closes 
		// the GUI using the button on the upper right corner	
		addWindowListener(new	WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				myAgent.doDelete();
			}
		} );
		
		setResizable(false);
	}
	
	public void showGui() {
		pack();
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		int centerX = (int)screenSize.getWidth() / 2;
		int centerY = (int)screenSize.getHeight() / 2;
		setLocation(centerX - getWidth() / 2, centerY - getHeight() / 2);
		super.setVisible(true);
	}

	public void setCommandReply(final String reply) {
		
		Runnable modifyGui = new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mReplyField.setText(reply);
				//this.repaint();	
			}
		};
		SwingUtilities.invokeLater(modifyGui);
	}
	
	public String getReplyText() {
		return mReplyField.getText();
	}
	
	private ClassifierAgent myAgent;
	private JTextField mCommandField;
	private JTextField mReplyField;
}
